<?php
defined('IN_PHPCMS') or exit('No permission resources.');
// 模型缓存路径
define('CACHE_MODEL_PATH', CACHE_PATH . 'caches_model' . DIRECTORY_SEPARATOR . 'caches_data' . DIRECTORY_SEPARATOR);
// 定义在单独操作内容的时候，同时更新相关栏目页面
define('RELATION_HTML', true);

pc_base::load_app_class('admin', 'admin', 0);
pc_base::load_sys_class('form', '', 0);
pc_base::load_app_func('util');
pc_base::load_sys_class('format', '', 0);

/**
 * 资讯绑定栏目
 */
class category extends admin
{

    private $db,$csmodel;

    public $siteid;

    public function __construct()
    {
        parent::__construct();
        $this->db = pc_base::load_model('news_nsr_model');
        $this->csmodel = pc_base::load_model('category_source_model');
        $this->siteid = get_siteid();
    }

    /**
     * 资讯绑定栏目列表
     */
    public function index()
    {
        if (! isset($_REQUEST['id']) || empty($_REQUEST['id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $source_type = $_REQUEST['source_type'];
        $show_dialog = $show_validator = true;
        $show_header = '';
        $id= $_REQUEST['id'];
        if ($source_type == 1) {
            $info = $this->db->get_one(array('id' => $id));
        } else if($source_type == 2){
            $video_model = pc_base::load_model('video_nsr_model');
            $info = $video_model->get_one(array('id' => $id));
        } else if($source_type == 3){
            $picture_model = pc_base::load_model('picture_nsr_model');
            $info = $picture_model->get_one(array('id' => $id)); 
        } 
        $models = getcache('model','commons');
        $types = array(0 => L('category_type_system'),1 => L('category_type_page'),2 => L('category_type_link'));

        $sql="select n.*,t.id as cid,t.is_top,t.sort from nsrweb_category_source as t LEFT JOIN nsrweb_category as n on t.cate_id =n.catid where t.source_type = " . $source_type;
        $sql .= " and  t.source_id=".$id." and n.siteid =" . $this->siteid;
        if (isset($_GET['catname']) && !empty($_GET['catname'])) {
            $catname = trim($_GET['catname']);
            $sql .= " and `catname` like '%$catname%' ";
        }
        $sql .= " order by t.is_top desc,t.sort desc ";
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;
        $contestinfo = $this->db->my_listinfo($sql, $page, 10);

        $pages = $this->db->pages;
        include $this->admin_tpl('category_list');
    }

    /**
     * 删除、批量删除
     */
    public function delete()
    {
        if (! isset($_REQUEST['id']) || empty($_REQUEST['id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $id = $_REQUEST['id'];
        $cate_id = array();
        if (is_array($id)) {
            foreach ($id as $k => $v) {
                if (intval($v)) {
                    $info = $this->csmodel->get_one(array('id'=>$v));
                    $source_id = $info['source_id'];
                    $cate_id[] = $info['cate_id'];
                    $source_name = $info['source_type'];
                    $id[$k] = intval($v);
                } else {
                    unset($id[$k]);
                }
            }
            $id = implode('\',\'', $id);
        } else {
            $info = $this->csmodel->get_one(array('id'=>$id));
            $source_id = $info['source_id'];
            $cate_id[] = $info['cate_id'];
            $source_name = $info['source_type'];
        }
        $result = $this->csmodel->delete("id in ('$id')");

        //记录行为日志
        $cate_id = implode(',',$cate_id);
        $source_name = $source_name == 1?'资讯':($source_name == 2?'视频':'图集');
        $log_content = '解除绑定关系[解除'.$source_name.'id：'.$source_id.'和栏目id：('.$cate_id.')的绑定]';
        $this->manage_admin_log($log_content);

        if ($result) {
            showmessage(L('operation_success'), HTTP_REFERER);
        } else {
            showmessage(L('operation_failure'), HTTP_REFERER);
        }
    }

    /**
     * 排序
     */
    public function listorder() {
        if(isset($_GET['dosubmit'])) {
            foreach($_POST['listorders'] as $id => $listorder) {
                $res = $this->csmodel->update(array('sort'=>$listorder), array('id'=>$id));
            }
            showmessage(L('operation_success'));
        } else {
            showmessage(L('operation_failure'));
        }
    }

    /**
     * 置顶
     */
    public function isTop ()
    {
        if (!isset($_REQUEST['id']) || empty($_REQUEST['id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $id= $_REQUEST['id'];
        $is_top = $_REQUEST['is_top'];
        $res = $this->csmodel->update(array('is_top'=>$is_top), array('id'=>$id));

        if ($res) {
            showmessage(L('operation_success'), HTTP_REFERER);
        } else {
            showmessage(L('operation_failure'), HTTP_REFERER);
        }
    }

    /**
     * 选择栏目绑定
     */
    public function bindCategory(){
        $id= $_REQUEST['id'];
        $source_type = $_REQUEST['source_type'];
        $show_pc_hash = '';
        $tree = pc_base::load_sys_class('tree');
        $models = getcache('model','commons');
        $sitelist = getcache('sitelist','commons');
        $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ','&nbsp;&nbsp;&nbsp;├─ ','&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        $categorys = array();
        //读取缓存
        $talent_array = $this->csmodel->select(array("source_id"=>$id,"source_type"=>$source_type),"cate_id");
        $ids = array();
        $where = ' type = 0 and siteid = ' . $this->siteid;
        if(!empty($talent_array)){
            foreach ($talent_array as $k => $v) {
                $ids[] = intval($v['cate_id']);
            }
        }
        $category_model = pc_base::load_model('category_model');
        $result = $category_model->select($where);
        $show_detail = count($result) < 500 ? 1 : 0;
        $parentid = $_GET['parentid'] ? intval($_GET['parentid']) : 0;
        $html_root = pc_base::load_config('system','html_root');
        $types = array(0 => L('category_type_system'),1 => L('category_type_page'),2 => L('category_type_link'));
        if(!empty($result)) {
            foreach($result as $r) {
                $r['modelname'] = $models[$r['modelid']]['name'];
                $r['typename'] = $types[$r['type']];
                $r['display_icon'] = $r['ismenu'] ? '' : ' <img src ="'.IMG_PATH.'icon/gear_disable.png" title="'.L('not_display_in_menu').'">';
                if(in_array($r['catid'],$ids)) {
                    $r['statusid'] = 1;
                    $r['statusname'] = '<span style="color:red;">已绑定</span>';
                } else {
                    $r['statusid'] = 0;
                    $r['statusname'] = '<span style="color:green;">未绑定</span>';
                }
                $categorys[$r['catid']] = $r;
            }
        }
        $str  = "<tr onclick='select_list(this,\$id)' class='cu' data='\$statusid' title='click_to_select'>
                    <td align='center'>\$id</td>
                    <td >\$spacer\$catname\$display_icon</td>
                    <td>\$typename</td>
                    <td>\$modelname</td>
                    <td>\$statusname</td>
                </tr>";
        $tree->init($categorys);
        $categorys = $tree->get_tree(0, $str);
        include $this->admin_tpl('bindCategory');
    }

    /**
     * 完成绑定
     */
    public function bindCategoryAjax(){
        $id= $_REQUEST['id'];
        $source_type = $_REQUEST['source_type'];
        $relation=$_REQUEST['relation'];
        $contest=explode("|",$relation);
        $data=array();
        foreach($contest as $k=>$v){
            $data[$k]['cate_id']=$v;
            $data[$k]['source_id']=$id;
            $data[$k]['source_type']=$source_type;
            $data[$k]['created_by'] =  $_SESSION['userid'];
            $data[$k]['updated_by'] =  $_SESSION['userid'];

            $data[$k]['create_time'] = date('Y-m-d H:i:s');
            $data[$k]['update_time'] = date('Y-m-d H:i:s');
        }
        $res = $this->csmodel->multiInsert($data);

        //记录行为日志
        $cate_id = implode(',',$contest);
        $source_name = ($source_type == 1?'资讯':($source_type == 2?'视频':'图集')).'id：'.$id;
        $log_content = '建立绑定关系['.$source_name.'和栏目id：('.$cate_id.')的绑定]';
        $this->manage_admin_log($log_content);

        if($res){
            echo json_encode(array("status"=>true,"code"=>200,"msg"=>"选择成功"));
        }else{
            echo json_encode(array("status"=>false,"code"=>1000,"msg"=>"选择失败"));
        }
    }
}